package com.my.socket.bio.v8;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by ZhongGang
 * at 2018/7/4 15:23
 */
public class Server implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private ServerSocket serverSocket;

    public Server(String host, int port) throws Exception {
        this.serverSocket = new ServerSocket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocket.bind(inetSocketAddress);
    }

    @Override
    public void run() {
        try {
            while (true) {
                try (Socket socket = this.serverSocket.accept()) {
                    LOGGER.info("incoming socket: {}", socket);

                    InputStream inputStream = socket.getInputStream();
                    String request = IOUtils.toString(inputStream, "UTF-8");
                    LOGGER.info("read: {}", request);
                    socket.shutdownInput();

                    OutputStream outputStream = socket.getOutputStream();
                    String response = request.toUpperCase();
                    IOUtils.write(response, outputStream, "UTF-8");
                    socket.shutdownOutput();
                    LOGGER.info("write: {}", response);
                } catch (Exception e) {
                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                }

            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        new Thread(server).start();
    }
}
